import os

from fastapi import FastAPI, HTTPException, status
from datetime import datetime
from fastapi.responses import FileResponse
from fastapi import HTTPException
from config import get_settings


def handle_log_file(thread_id):
    # 确保日志目录存在
    #LOG_FILES_DIRECTORY="D:\\AI\\code\\ETL_agent\\app\\logs\\user\\"

    #需要替换自己的日志文件路径
    #LOG_FILES_DIRECTORY="D:\\AI\\code\\ETL_agent\\app\\logs\\user\\"
    today = datetime.now().strftime('%Y%m%d')

    log_file_path = os.path.join(get_settings().log_files_directory, f'{thread_id}-{today}.log')

    # 检查文件是否存在
    if not os.path.exists(log_file_path):
        raise HTTPException(status_code=404, detail=f"接口 '{log_file_path}' 的日志文件不存在")

    # 检查是否是文件
    if not os.path.isfile(log_file_path):
        raise HTTPException(status_code=400, detail=f"指定路径不是文件: {log_file_path}")

    try:
        # 读取文件全部内容
        with open(log_file_path, "r", encoding="utf-8") as file:
            content = file.read()
        return {
            "thread_id": thread_id,
            "content": content
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"读取文件时发生错误: {str(e)}")


def handle_report_file(thread_id):
    # 确保日志目录存在
    #LOG_FILES_DIRECTORY="D:\\AI\\code\\ETL_agent\\"

    #需要替换自己的日志文件路径
    #LOG_FILES_DIRECTORY="D:\\AI\\code\\ETL_agent\\app\\logs\\user\\"

    log_file_path = os.path.join(get_settings().log_files_re_directory, f'{thread_id}.md')

    # 检查文件是否存在
    if not os.path.exists(log_file_path):
        raise HTTPException(status_code=404, detail=f"接口 '{log_file_path}' 的日志文件不存在")

    # 检查是否是文件
    if not os.path.isfile(log_file_path):
        raise HTTPException(status_code=400, detail=f"指定路径不是文件: {log_file_path}")

    try:
        # 读取文件全部内容
        with open(log_file_path, "r", encoding="utf-8") as file:
            content = file.read()
        return {
            "thread_id": thread_id,
            "content": content
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"读取文件时发生错误: {str(e)}")


def handle_log_number_file(thread_id, line_number):
        # 确保日志目录存在
        #LOG_FILES_DIRECTORY="D:\\AI\\code\\ETL_agent\\app\\logs\\user\\"

        #需要替换自己的日志文件路径
        #LOG_FILES_DIRECTORY="D:\\AI\\code\\ETL_agent\\app\\logs\\user\\"
        today = datetime.now().strftime('%Y%m%d')

        log_file_path = os.path.join(get_settings().log_files_directory, f'{thread_id}-{today}.log')

        # 检查文件是否存在
        if not os.path.exists(log_file_path):
            raise HTTPException(status_code=404, detail=f"接口 '{log_file_path}' 的日志文件不存在")

        # 检查是否是文件
        if not os.path.isfile(log_file_path):
            raise HTTPException(status_code=400, detail=f"指定路径不是文件: {log_file_path}")

        try:
            # 读取指定行号的内容
            with open(log_file_path, "r", encoding="utf-8") as file:
                # 行号从1开始计数
                for current_line, line_content in enumerate(file, 1):
                    if current_line == line_number:
                        content = line_content.strip()  # 去除换行符和前后空白
                        break
                else:
                    # 如果循环结束仍未找到指定行号
                    raise HTTPException(status_code=404, detail=f"文件中不存在行号 {line_number}")

            return {
                "thread_id": thread_id,
                "line_number": line_number,
                "content": content
            }
        except HTTPException:
            # 重新抛出已定义的HTTP异常
            raise
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"读取文件时发生错误: {str(e)}")


def download_file(thread_id):

    LOG_FILES_DIRECTORY="D:\\AI\\code\\ETL_agent\\app\\"

    #需要替换自己的日志文件路径
    #LOG_FILES_DIRECTORY="D:\\AI\\code\\ETL_agent\\app\\logs\\user\\"

    file_path = os.path.join(LOG_FILES_DIRECTORY, f'{thread_id}.pdf')

    # 检查文件是否存在
    if not os.path.exists(file_path) or not os.path.isfile(file_path):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"文件 '{thread_id}' 不存在"
        )

    # 返回文件响应
    return FileResponse(
        path=file_path,
        filename=f'{thread_id}.pdf',
        media_type="application/octet-stream"
    )
